package com.xiaoerkeji.eshop.update;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.xiaoerkeji.eshop.utils.CommandUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class AppUpdater {
    private static final String TAG = "AppUpdater";
    private Activity activity;
    private Context context;
    private String updateUrl;
    private String apkUrl;
    private String apkName;
    private long downloadId;
    private DownloadCompleteReceiver receiver;

    public AppUpdater(Activity activity, Context context, String updateUrl) {
        this.activity = activity;
        this.context = context;
        this.updateUrl = updateUrl;
        this.apkName = "update_" + System.currentTimeMillis() + ".apk";
        this.receiver = new DownloadCompleteReceiver();
    }

    //检查自动升级
    public void checkForUpdates() {
        new Thread(() -> {
            try {
                URL url = new URL(updateUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                String str = reader.readLine();

                JSONObject json = new JSONObject(str);
                double latestVersion = json.getDouble("version");
                apkUrl = json.getString("url");
                double currentVersion =  context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;

                if (latestVersion > currentVersion) {
                    activity.runOnUiThread(() -> {
                        showUpdateDialog();
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    //显示升级对话框
    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("发现新版本")
                .setMessage("是否立即更新？")
                .setPositiveButton("更新", (dialog, which) -> {
                    startDownload();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    public void startDownload() {
        File apkFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);

        if (apkFile.exists()) {
            apkFile.delete();
        }

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
        request.setTitle("应用更新");
        request.setDescription("正在下载新版本");
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadId = downloadManager.enqueue(request);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE), context.RECEIVER_EXPORTED);
        }
    }

    private class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            long receivedId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (downloadId == receivedId) {
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(receivedId);

                DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                Cursor cursor = downloadManager.query(query);

                if (cursor.moveToFirst()) {
                    @SuppressLint("Range") int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    if (status == DownloadManager.STATUS_SUCCESSFUL) {
                        installApk();
                    } else {
                        Log.e(TAG, "下载失败: " + status);
                    }
                }
                cursor.close();
                context.unregisterReceiver(this);
            }
        }
    }

    private void installApk() {
        File apkFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, "com.xiaoerkeji.eshop.fileprovider", new File(apkFile.toURI()));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(apkName)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }
}
